package com.cmy.framework_network.apiresponse

import com.cmy.framework_network.base.Envelope
import com.cmy.framework_network.error.BusinessException
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter

class ResultTypeAdapter<T>(
    private val dataTypeAdapter: JsonAdapter<T>,
    private val envelope: Envelope?
) : JsonAdapter<T>() {
    override fun fromJson(reader: JsonReader): T? {
        if (envelope != null) {
            reader.beginObject()
            var errcode: Int? = null
            var msg: String? = null
            var data: Any? = null

            while (reader.hasNext()) {
                when (reader.nextName()) {
                    envelope.getStatusCodeKey() -> errcode = reader.nextString().toIntOrNull()
                    envelope.getErrorMessageKey() -> msg = reader.nextString()
                    envelope.getDataKey() -> data = dataTypeAdapter.fromJson(reader)
                    else -> reader.skipValue()
                }
            }
            reader.endObject()
            if (errcode == null)
                throw JsonDataException("Expected field [errcode] not present.")

            return if (envelope.doesStatusCodeIndicateSuccess(errcode)) data as T
            else throw BusinessException(errcode, msg)
        } else {
            return dataTypeAdapter.fromJson(reader) as T
        }
    }

    override fun toJson(writer: JsonWriter, value: T?): Unit = TODO("Not yet implemented")
}